// pages/index/search/search.js
import util from "../../../utils/utils";
import Data from "../../../utils/data";
Page({
  data:{
    value:'',
    initUser:false,
    userInfo:{},
    currentTab:0,
    platform:1,
    searchHistory:[],
    hotSearch:[],
  },
  /**
   * 页面载入完成
   */
  initPage: function(){
    wx.hideShareMenu();
    this.initData();
  },
  clearLog:function(){
    util.cache_remove('search_log');
    this.setData({
      searchHistory:[],
    });
  },
  switchPlatform: function(event){
    let detail = event.detail;
    this.setData({
      currentTab:detail.index,
      platform:detail.itemid
    });
  },
  onShow:function(){
    let _history  = [];
    let cache_log = util.cache_get('search_log');
    if(cache_log){
      for(let i = cache_log.length-1;i>=0;i--){
        if(_history.length >= 18){
          break;
        }
        cache_log[i] = cache_log[i].trim();
        if(cache_log[i].length > 0){
          _history.push(cache_log[i]);
        }
      }
    }
    this.setData({
      searchHistory:_history,
    });
  },
  onChange:function(e) {
    this.setData({
      value: e.detail
    });
  },
  onSearch:function(event) {
    let cache_log  = util.cache_get('search_log');
    let push_cache = true;
    if(this.data.value === ''){
      util.msg('请输入要搜索的关键词!');
      return false;
    }
    if(cache_log){
      for(let i = 0;i<cache_log.length;i++){
        if(cache_log[i] === this.data.value){
          push_cache = false;
        }
      }
      if(push_cache === true){
        cache_log.push(this.data.value);
      }
    }else{
      cache_log = [this.data.value];
    }
    wx.navigateTo({
      url: '/pages/index/search/detail/index?platform='+this.data.platform+'&currentTab='+this.data.currentTab+'&keyword=' + this.data.value
    });
    util.cache_put('search_log',cache_log);
  },
  initData: function(ref){
    let self = this;
    /**
     * 拉取热门搜索推荐
     */
    Data.getHotSearch(function(result){
      let _history  = [];
      let cache_log = util.cache_get('search_log');
      if(cache_log){
        for(let i = cache_log.length-1;i>=0;i--){
          if(_history.length >= 18){
            break;
          }
          cache_log[i] = cache_log[i].trim();
          if(cache_log[i].length > 0){
            _history.push(cache_log[i]);
          }
        }
      }
      self.setData({
        hotSearch:result,
        searchHistory:_history,
      });
    },true);
  }
});
